<?php

namespace App\Http\Controllers\Steward;

use App\Models\Goods\GoodsSale;
use App\Models\Goods\StewardGoodsDown;
use App\Models\Goods\StewardGoodsstoreDown;
use App\Models\Goods\WmsGoodsMaster;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\Goods\GoodsStore;
use App\Models\Goods\GoodsMaster;
use App\Models\Mall\MallMaster;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis as Redis;
use Maatwebsite\Excel\Facades\Excel;
use Mockery\CountValidator\Exception;
use Carbon\Carbon;

class StockController extends Controller
{

    //库存列表
    public function index(Request $request)
    {
     return view('steward/goods/stock/index');
    }


    //库存列表数据查询
    public function search( Request $request)
    {
        $rp      = $request->input('rp',10);
        $offset=$request->input('offset',0);
        $return_data=[];
        $result_data = [
            'total' =>0,
            'rows' =>$return_data
        ];

       $mallID    =Redis::get('WDH_STEWARD_MALL_ID_' . session_id());
        $where=[];
        //商家编码
        if($request->input('product_code')){
            $where[] = ['product_code',$request->input('product_code')];
        }

        //商品名称
        if($request->input('goodsName')){
            $where[] = ['goodsName','like','%'.$request->input('goodsName').'%'];
        }

        //商品库存
        if($request->input('store_start')   ){
            $where[] = ['enableSaleAmount','>=',$request->input('store_start')];

        }
        if( $request->input('store_end')){
            $where[] = ['enableSaleAmount','<=',$request->input('store_end')];
        }
        //查询库存信息
        $store_data= GoodsStore::where('storeID',$mallID)->where($where)->offset($offset)->limit($rp)->get()->toArray();
        $total_store_data=GoodsStore::where('storeID',$mallID)->where($where)->get()->toArray();

        $total=count($total_store_data);

        if($store_data!=array())
        {
            foreach($store_data as $key=> $value)
            {
                $product_code=$value['product_code'];

                //查询销售商品信息
                $goods_sale=GoodsSale::where('product_code',$product_code)->get()->toArray();

                if($goods_sale)
                {
                    $spec=$goods_sale[0]['spec'];
                }else{
                    $spec='';
                }

                $return_data[]=array(
                    'operation'=>'<a href="javascript:void(0)" class="delete"  data_type="' . $value['mainPostID']. '" data_id="' . $product_code . '">删除</a>',
                    'goodsName'=>$value['goodsName'],//商品名称
                    'product_code'=>$product_code,
                    'spec'=>$spec,
                    'enableSaleAmount'=> '<span id="1'.$product_code.'">'.$value['enableSaleAmount'].'&nbsp;<a href="javascript:void(0)" class="update" data_type="1" data_id="' . $product_code . '" data="'.$value['enableSaleAmount'].'"><span class="glyphicon glyphicon-pencil"></span></a></span>',//可售库存
                    'lockAmount'=>$value['lockAmount'],//锁定库存
                    'virtualAmount'=> '<span id="2'.$product_code.'">'.$value['virtualAmount'].'&nbsp;<a href="javascript:void(0)" class="update" data_type="2" data_id="' . $product_code . '" data="'.$value['virtualAmount'].'"><span class="glyphicon glyphicon-pencil"></span></a></span>',//虚拟库存
                    'timeStamp'=>'<span id="t_'.$value['product_code'].'">'.$value['timeStamp'].'</span>'
                );
            }
            $result_data = [
                'total' =>$total,
                'rows' =>$return_data
            ];
        }
        return $result_data;
    }

    //删除库存信息
    public function deletes( Request $request)
    {
        $mallID    =Redis::get('WDH_STEWARD_MALL_ID_' . session_id());
        $del_arr=$request['data'];

        if(empty($del_arr))
        {
            return response()->json(['code'=>10001, 'message'=>'缺少参数']);
        }

        foreach($del_arr as &$val)
        {
            $data = explode(',',$val);
            $val = array();
            $val['storeID'] = $mallID;
            $val['product_code'] = isset($data[0])?$data[0]:'';
            $val['mainPostID'] = isset($data[1])?$data[1]:'';
        }

        try {

            //开启事务
            DB::beginTransaction();

            foreach ( $del_arr as $store ){
                //删除商品库存信息
                DB::delete('delete from wms_goodsstore where product_code = ? and storeID =? ',[$store['product_code'],$mallID]);

                //查询商品库存信息
                $goodsstore_data=GoodsStore::where('mainPostID','=',$store['mainPostID'])->where('storeID','=',$mallID)->get()->toArray();
                if ( !$goodsstore_data ) {
                    //删除主商品库存信息
                    DB::delete('delete from wms_goods_master where mainPostID = ? and storeID =? ',[$store['mainPostID'],$mallID]);
                }
            }
            //提交事务
            DB::commit();

            return array('code'=> 200 , 'message'=> '商品库存删除成功');

        } catch (Exception $e) {
            //回滚事务
            DB::rollBack();
            return array('code'=> 10001 , 'message'=> '商品库存删除失败');
        }

    }


    //修改库存
    public function update( Request $request)
    {
        $type=$request->input('type');
        $product_code=$request->input('product_code');
        $stock=$request->input('stock');
        $mallID    =Redis::get('WDH_STEWARD_MALL_ID_' . session_id());
        $update_stock='';
        $message='';
        if($type==1)
        {
            $update_stock='enableSaleAmount';
            $message='修改可售库存成功';
        }
        if($type==2)
        {
            $update_stock='virtualAmount';
            $message='修改虚拟库存成功';
        }

        $time=date('Y-m-d h:i:s');
        $res= DB::update('update wms_goodsstore set '.$update_stock.' = ? , `timeStamp` = ? where product_code  = ?  and storeID = ?',[$stock,$time,$product_code,$mallID]);
        if($res)
        {
            return response()->json(['code'=>200, 'message'=>$message,'data'=>$time]);
            }
    }

    /**
     * 库存批量上传
     */
    public function batchStock(){

        return view('steward/goods/batch/stock');

    }

    /**
     * 库存模板导出
     */
    public function export(){

        return response()->download(resource_path().'/goods_stock.xls', '库存上传模板.xls');
    }

    /**
     * 库存批量添加
     */
    public function batchDo(Request $request)
    {

        $mall_id = Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) ? Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) : 0;

        $url = 'public' . $request->input('file_url');
        $count_success = 0;
        $count_fail = 0;

        Excel::load($url, function ($reader) use($mall_id,&$count_success,&$count_fail) {

            $data = $reader->getSheet();

            if($data){

                $data = $data->toArray();
                unset($data[0]);
            }

            foreach ($data as $item){

                if(empty($item[0]) || empty($item[1]) ){

                    $count_fail ++;
                    continue;
                }

                $p_id = (int)$item[0];
                $amount = (int)$item[1];

                $stewardGoodsData = StewardGoodsstoreDown::where([['product_code',$p_id],['storeID',$mall_id]])->first();
                $wmsGoodsData = GoodsStore::where([['product_code',$p_id],['storeID',$mall_id]])->first();

                if($stewardGoodsData){  //商品禁用状态

                    $stewardGoodsData = $stewardGoodsData->toArray();
                    StewardGoodsstoreDown::where([['product_code',$p_id],['storeID',$mall_id]])->delete();

                    $wmsGoodsstore = new GoodsStore();
                    $wmsGoodsstore->uuid = Uuid::uuid();
                    $wmsGoodsstore->timeStamp = date('Y-m-d h:i:s');
                    $wmsGoodsstore->creator = $stewardGoodsData['creator'];
                    $wmsGoodsstore->createTime = date('Y-m-d h:i:s');
                    $wmsGoodsstore->mainPostID = $stewardGoodsData['mainPostID'];
                    $wmsGoodsstore->storeID = $stewardGoodsData['storeID'];
                    $wmsGoodsstore->product_code = $stewardGoodsData['product_code'];
                    $wmsGoodsstore->goodsName = $stewardGoodsData['goodsName'];
                    $wmsGoodsstore->enableSaleAmount = $amount;
                    $wmsGoodsstore->lockAmount = $stewardGoodsData['lockAmount'];
                    $wmsGoodsstore->badAmount = $stewardGoodsData['badAmount'];
                    $wmsGoodsstore->virtualAmount = $stewardGoodsData['virtualAmount'];
                    $wmsGoodsstore->saleAmount = $stewardGoodsData['saleAmount'];
                    $wmsGoodsstore->lastAmount = $stewardGoodsData['lastAmount'];
                    $wmsGoodsstore->shelfID = $stewardGoodsData['shelfID'];
                    $wmsGoodsstore->sync_offline_stock = $stewardGoodsData['sync_offline_stock'];
                    $wmsGoodsstore->forsale = $stewardGoodsData['forsale'];
                    $wmsGoodsstore->save();

                    $count_success++;

                    $steward_goods_down = StewardGoodsDown::where([['mainPostID',$stewardGoodsData['mainPostID']],['storeID',$mall_id]])->first();

                    if($steward_goods_down){   //主商品禁用状态

                        StewardGoodsDown::where([['mainPostID',$stewardGoodsData['mainPostID']],['storeID',$mall_id]])->delete();

                        $wms_goods_master = new WmsGoodsMaster();
                        $wms_goods_master->uuid = Uuid::uuid();
                        $wms_goods_master->timeStamp = date('Y-m-d h:i:s');
                        $wms_goods_master->creator = 'system';
                        $wms_goods_master->createTime = date('Y-m-d h:i:s');
                        $wms_goods_master->storeID = $mall_id;
                        $wms_goods_master->mainPostID = $stewardGoodsData['mainPostID'];
                        $wms_goods_master->save();
                    }
                }elseif ($wmsGoodsData) {  //商品启用状态

                    GoodsStore::where('product_code',$p_id)->where('storeID',$mall_id)->update(['enableSaleAmount'=>$amount]);
                    $count_success++;

                }else{                  //商品选品

                    $goods_sale_data = GoodsSale::find($p_id);
                    if($goods_sale_data){

                        $goods_sale_data = $goods_sale_data->toArray();

                        $wms_goods_master = new WmsGoodsMaster();
                        $wms_goods_master->uuid = Uuid::uuid();
                        $wms_goods_master->timeStamp = date('Y-m-d h:i:s');
                        $wms_goods_master->creator = 'system';
                        $wms_goods_master->createTime = date('Y-m-d h:i:s');
                        $wms_goods_master->storeID = $mall_id;
                        $wms_goods_master->mainPostID = $goods_sale_data['mainPostID'];
                        $wms_goods_master->save();

                        $wmsGoodsstore = new GoodsStore();
                        $wmsGoodsstore->uuid = Uuid::uuid();
                        $wmsGoodsstore->timeStamp = date('Y-m-d h:i:s');
                        $wmsGoodsstore->creator = 'system';
                        $wmsGoodsstore->createTime = date('Y-m-d h:i:s');
                        $wmsGoodsstore->mainPostID = $goods_sale_data['mainPostID'];
                        $wmsGoodsstore->storeID = $mall_id;
                        $wmsGoodsstore->product_code = $goods_sale_data['product_code'];
                        $wmsGoodsstore->goodsName = $goods_sale_data['goodsName'];
                        $wmsGoodsstore->enableSaleAmount = $amount;
                        $wmsGoodsstore->lockAmount = 0;
                        $wmsGoodsstore->badAmount = 0;
                        $wmsGoodsstore->virtualAmount = 0;
                        $wmsGoodsstore->saleAmount = 0;
                        $wmsGoodsstore->lastAmount = 0;
                        $wmsGoodsstore->shelfID = 0;
                        $wmsGoodsstore->sync_offline_stock = 1;
                        $wmsGoodsstore->forsale = $goods_sale_data['forsale'];
                        $wmsGoodsstore->save();

                        $count_success++;
                    }else{

                       $count_fail++;
                    }
                }
            }
        });

        unlink(public_path().$request->input('file_url'));

        return response()->json(['code' => 200,'message' => $count_success.'个商品操作成功,'.$count_fail.'个商品操作失败']);
    }
}